package com.zx.cloud.util;

import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

public class UniqueIdGenerator {

	private static int count = 0;
	private static final int lastIp;
	private static final Map<Long, Long> lastId = new LinkedHashMap<Long, Long>() {
		private static final long serialVersionUID = 1L;

		protected boolean removeEldestEntry(Map.Entry<Long, Long> eldest) {
			return size() > 1000;
		}
	};

	public static String getExternalVariable(String var) {
		String value = System.getenv(var);
		if (StringUtils.isEmpty(value)) {
			value = System.getProperty(var);
		}
		if (StringUtils.isEmpty(value)) {
			value = null;
		}
		return value;
	}

	static {
		String id = getExternalVariable("JAVA_UTIL_CLUSTERID");
		if (StringUtils.isEmpty(id)) {
			lastIp = 99;
		} else {
			try {
				lastIp = Integer.parseInt(id) % 100;
			} catch (NumberFormatException e) {
				throw new IllegalArgumentException("Environment / System variable JAVA_UTIL_CLUSTERID must be 0-99");
			}
		}
	}

	public static long getUniqueId() {
		synchronized (UniqueIdGenerator.class) {
			long newId = getUniqueIdAttempt();
			while (lastId.containsKey(newId)) {
				newId = getUniqueIdAttempt();
			}
			lastId.put(newId, null);
			return newId;
		}
	}

	private static long getUniqueIdAttempt() {
		count++;
		if (count >= 1000) {
			count = 0;
		}
		return System.currentTimeMillis() * 100000 + count * 100 + lastIp;
	}
}
